﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using OpenRasta.Codecs;
using OpenRasta.Web;
using OpenRasta.TypeSystem;
using Newtonsoft.Json;

namespace uREST.Core.Codecs
{
    [MediaType("application/json;q=0.5", "json")]
    public class JsonNetCodec : IMediaTypeReader, IMediaTypeWriter
    {
        public object Configuration { get; set; }

        public object ReadFrom(IHttpEntity request, IType destinationType, string destinationName)
        {
            using (var sr = new StreamReader(request.Stream))
            using (var jr = new JsonTextReader(sr))
            {
                var serializer = new JsonSerializer();
                //serializer.Converters.Add(new IsoDateTimeConverter());
                return serializer.Deserialize(jr, destinationType.StaticType);
            }
        }

        public void WriteTo(object entity, IHttpEntity response, string[] codecParameters)
        {
            if (entity == null)
                return;

            using (var sw = new StreamWriter(response.Stream))
            using (var jw = new JsonTextWriter(sw))
            {
                jw.Formatting = Formatting.Indented;

                var serializer = new JsonSerializer();
                //serializer.Converters.Add(new IsoDateTimeConverter());
                serializer.Serialize(sw, entity);
            }
        }
    }
}
